package com.xu.demo.feature.blog;

import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

public class PhotoUtils {
    /**
     * 扫描相册文件所在的根目录 ， 例如: D:/data/pic/pic
     */
    private static final String photoFilePathRoot = "D:\\data\\pic\\pic";

    /**
     * 映射相册文件所在的网络路径 ， 例如: http://localhost:8081, 取决于nginx配置的路径
     */
    private static final String photoUrlPathRoot = "http://localhost:8081";

    /**
     * 相册文件输出目录
     */
    private static final String photoOuterFilePath = "D:\\worker\\vscode\\blog\\source\\photo\\";


    public static void main(String[] args) throws IOException {
        File rootFolder = new File(photoFilePathRoot);

        Map<Integer, List<File>> folderMap = new HashMap<>();
        {// 初始化第一层
            File[] folder = rootFolder.listFiles();
            assert folder != null;
            List<File> tmp = new ArrayList<>(Arrays.asList(folder));
            folderMap.put(1, tmp);
        }

        Map<String, PhotoData> result = new HashMap<>();
        int totalLevel = 1;
        for (int photoLevel = 1; photoLevel <= totalLevel; photoLevel++) {
            List<File> files = folderMap.get(photoLevel);
            if(files == null) continue;

            for (File file : files) {
                if (file.isFile()) {// 是文件
                    String path = file.toString();
                    String replace = path.replace(photoFilePathRoot, "").replace("\\", "/");

                    String[] split = replace.split("/");
                    String currPath = split[split.length-2];
                    StringBuilder fullPath = new StringBuilder();
                    for (int i = 0; i < split.length-1; i++) {

                        if(!StringUtils.isEmpty(split[i])) {
                            if(fullPath.length()>0) fullPath.append("_");
                            fullPath.append(split[i]);
                        }
                    }

                    PhotoData tmp;
                    if(result.containsKey(fullPath.toString())){
                        tmp = result.get(fullPath.toString());
                    }else {
                        tmp = new PhotoData();
                        tmp.setPhotos(new ArrayList<>());
                        tmp.setCurrPath(currPath);
                        tmp.setFullPath(fullPath.toString());
                        result.put(fullPath.toString(), tmp);
                    }

                    tmp.getPhotos().add(photoUrlPathRoot + replace);
                } else {// 是文件夹
                    totalLevel++;

                    List<File> nextLevelFolder;
                    if (folderMap.containsKey(totalLevel)) {
                        nextLevelFolder = folderMap.get(totalLevel);
                    }
                    else {
                        nextLevelFolder = new ArrayList<>();
                        folderMap.put(totalLevel, nextLevelFolder);
                    }

                    {// 避免命名重复
                        File[] arr = file.listFiles();
                        if (arr == null) continue;
                        List<File> tmp = new ArrayList<>(Arrays.asList(arr));
                        nextLevelFolder.addAll(tmp);
                    }

                }
            }
        }

        {
            File file = new File(photoOuterFilePath);
            if (file.exists()) {
                file.delete();
            }
            file.mkdirs();
        }


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String nowDate = sdf.format(new Date());
        // 输出模板
        {
            StringBuilder template = new StringBuilder();
            template.append("---").append("\r\n");
            template.append("title: photo").append("\r\n");
            template.append("date: ").append(nowDate).append("\r\n");
            template.append("updated: ").append(nowDate).append("\r\n");
            template.append("---").append("\r\n");

            template.append("<div class=\"gallery-group-main\">").append("\r\n");
            for (String key : result.keySet()) {
                PhotoData photoData = result.get(key);
                template.append(String.format("{%% galleryGroup '%s' '%s' '%s' '%s' %%}", photoData.getFullPath(), photoData.getFullPath(), "/photo/"+photoData.getFullPath(), photoData.getPhotos().get(0))).append("\r\n");
            }
            template.append("</div>").append("\r\n");
        
            File file = new File(photoOuterFilePath + "index.md");
            if(!file.exists()){
                file.createNewFile();

            }
            FileWriter writer = new FileWriter(file);
            writer.write(template.toString());
            writer.close();
        }

        // 输出模板
        {
            for (String key : result.keySet()) {
                PhotoData photoData = result.get(key);

                StringBuilder template = new StringBuilder();
                template.append("---").append("\r\n");
                template.append("title: ").append(photoData.getFullPath()).append("\r\n");
                template.append("date: ").append(nowDate).append("\r\n");
                template.append("updated: ").append(nowDate).append("\r\n");
                template.append("---").append("\r\n");

                template.append("{% gallery %}").append("\r\n");

                List<String> photos = photoData.getPhotos();
                for (String photo : photos) {
                    template.append(String.format("![](%s)", photo)).append("\r\n");
                }
                template.append("{% endgallery %}").append("\r\n");

                File file = new File(photoOuterFilePath + photoData.getFullPath()+".md");
                if(!file.exists()){
                    file.createNewFile();
                }
                FileWriter writer = new FileWriter(file);
                writer.write(template.toString());
                writer.close();
            }
        }

    }

    @Data
    static class PhotoData{
        /**
         * 层级
         */
        private int level;

        /**
         * 本层级相册的路径
         */
        private String currPath;

        /**
         * 本相册相对 Root 路径的完整路径
         */
        private String fullPath;

        /**
         * 图片列表
         */
        private List<String> photos;
    }
}
